#include <iostream>
#include <string>
#include <time.h>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

void Usage(const std::string& proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n" << std::endl;
}

// ./clientcal ip port
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip, serverport);
    if(!r)  return 1;

    srand(time(0)^getpid());
    int cnt = 1;
    const std::string opers = "+-*/%^&";
    std::string inbuffer_stream;

    while(cnt <= 10)
    {
        printf("================= 第%d次测试=========\n", cnt++);
        int x = rand()%50+1;
        usleep(1000);
        int y = rand()%30;
        usleep(1000);
        char op = opers[rand()%opers.size()];

        Request req(x, y, op);      // 开始请求询问相应
        req.DebugPrint();

        std::string package;
        req.Serialize(&package);
        package = Encode(package);  // 构建网络报文

        write(sockfd.Fd(), package.c_str(), package.size());    // 向套接字文件内写入（传到网络内部）

        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;  // "len"\n"result code"\n
            std::cout << inbuffer_stream << std::endl;

            std::string content;
            bool r = Decode(inbuffer_stream, &content);     // 开始解码
            if(!r) return 2;

            Response resp;      // 获取相应过来的数据报文
            r = resp.Deserialize(content);  // 反序列化 
            if(!r) return 3;

            resp.DebugPrint();
        }
        std::cout << "==================================" << std::endl;
        sleep(1);
    }

    sockfd.Close();
    return 0;
}

